<template>
  <div class="login-bg">
    <div class="login-container">
      <div class="login-box">
        <img class="login-logo" src="\src\assets\icon.png" alt="logo" />
        <h2>智慧医保报销系统</h2>
        <form @submit.prevent="handleLogin">
          <div class="form-group">
            <input v-model="loginForm.username" placeholder="用户名" required :disabled="loading" />
          </div>
          <div class="form-group">
            <input v-model="loginForm.password" type="password" placeholder="密码" required :disabled="loading" />
          </div>
          <div class="captcha-row">
            <input 
              v-model="loginForm.captcha" 
              placeholder="验证码" 
              maxlength="4" 
              required 
              :disabled="loading"
            />
            <img 
              v-if="captchaImage" 
              :src="captchaImage" 
              class="captcha-img" 
              @click="refreshCaptcha" 
              alt="验证码"
            />
            <span v-else class="captcha-placeholder" @click="refreshCaptcha">
              点击获取验证码
            </span>
          </div>
          <button type="submit" :disabled="loading">
            {{ loading ? '登录中...' : '登录' }}
          </button>
          <div v-if="error" class="error">{{ error }}</div>
        </form>
        
        <!-- 测试账号提示 -->
        <div class="test-accounts">
          <h4>测试账号：</h4>
          <div class="account-item">
            <strong>超级管理员：</strong>admin / 123456
          </div>
          <div class="account-item">
            <strong>医保信息维护员：</strong>medical_admin / 123456
          </div>
          <div class="account-item">
            <strong>医院医生：</strong>doctor_001 / 123456
          </div>
          <div class="account-item">
            <strong>医保中心管理员：</strong>insurance_admin / 123456
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getCaptcha } from '@/api/auth'
import { login } from '@/store/user'

const router = useRouter()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  captchaKey: ''
})

// 验证码相关
const captchaImage = ref('')
const loading = ref(false)
const error = ref('')

// 获取验证码
const refreshCaptcha = async () => {
  try {
    console.log('=== 开始获取后端验证码 ===')
    console.log('请求URL: http://localhost:8080/ybbx/auth/captcha')
    
    const response = await getCaptcha()
    
    console.log('=== 后端验证码响应详情 ===')
    console.log('响应类型:', typeof response)
    console.log('响应内容:', JSON.stringify(response, null, 2))
    
    // 检查响应是否存在
    if (!response) {
      throw new Error('后端返回空响应')
    }
    
    // 根据实际后端响应格式解析: { flag: true, data: { captchaKey, captchaImage } }
    if (response.flag === true && response.data) {
      const { captchaKey, captchaImage: captchaImageData } = response.data
      console.log('解析后端响应:')
      console.log('- captchaKey:', captchaKey)
      console.log('- captchaImage前缀:', captchaImageData ? captchaImageData.substring(0, 50) + '...' : 'null')
      
      if (captchaImageData && captchaKey) {
        captchaImage.value = captchaImageData
        loginForm.captchaKey = captchaKey
        console.log('✅ 后端验证码设置成功!')
        ElMessage.success('验证码获取成功')
        return
      } else {
        throw new Error('后端响应中缺少captchaImage或captchaKey字段')
      }
    } else {
      throw new Error(`后端返回失败: flag=${response.flag}, message=${response.message}`)
    }
    
  } catch (err) {
    console.error('=== 获取后端验证码失败 ===')
    console.error('错误类型:', err.constructor.name)
    console.error('错误消息:', err.message)
    console.error('错误详情:', err)
    
    if (err.response) {
      console.error('HTTP状态码:', err.response.status)
      console.error('HTTP响应:', err.response.data)
    }
    
    ElMessage.error(`获取验证码失败: ${err.message}`)
    
    // 清空验证码显示
    captchaImage.value = ''
    loginForm.captchaKey = ''
  }
}

// 处理登录
const handleLogin = async () => {
  if (loading.value) return
  
  error.value = ''
  loading.value = true
  
  try {
    // 表单验证
    if (!loginForm.username.trim()) {
      throw new Error('请输入用户名')
    }
    if (!loginForm.password.trim()) {
      throw new Error('请输入密码')
    }
    if (!loginForm.captcha.trim()) {
      throw new Error('请输入验证码')
    }
    
    // 准备登录数据
    const loginData = {
      username: loginForm.username.trim(),
      password: loginForm.password.trim(),
      captcha: loginForm.captcha.trim(),
      captchaKey: loginForm.captchaKey || 'mock_key'
    }
    
    console.log('发送登录请求:', { ...loginData, password: '***' })
    
    // 调用登录API
    const response = await login(loginData)
    console.log('登录响应:', response)
    
    ElMessage.success('登录成功')
    
    // 根据用户角色跳转到对应页面
    const userRole = response.userInfo?.roles?.[0]?.roleKey || response.data?.userInfo?.roles?.[0]?.roleKey
    
    if (userRole === 'admin') {
      router.push('/system')
    } else if (userRole === 'medical_info_admin') {
      router.push('/medical-info')
    } else if (userRole === 'hospital_doctor') {
      router.push('/hospital-doctor')
    } else if (userRole === 'insurance_center_admin') {
      router.push('/insurance-center')
    } else {
      router.push('/medical-info') // 默认跳转
    }
    
  } catch (err) {
    console.error('登录失败:', err)
    
    // 分析错误类型
    if (err.message?.includes('验证码')) {
      error.value = '验证码错误，请重新输入'
      ElMessage.error('验证码错误')
    } else if (err.message?.includes('用户名') || err.message?.includes('密码')) {
      error.value = '用户名或密码错误'
      ElMessage.error('用户名或密码错误')
    } else {
      error.value = err.message || '登录失败，请检查用户名和密码'
      ElMessage.error(error.value)
    }
    
    // 登录失败后刷新验证码
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 页面加载时获取验证码
onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #74ebd5 0%, #ACB6E5 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
}

.login-box {
  background: #fff;
  padding: 40px 32px 32px 32px;
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  min-width: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.login-logo {
  width: 60px;
  margin-bottom: 16px;
}

.login-box h2 {
  margin-bottom: 24px;
  text-align: center;
  color: #34495e;
  font-weight: 700;
  letter-spacing: 2px;
  font-size: 22px;
}

.form-group {
  width: 100%;
  margin-bottom: 18px;
}

.login-box input {
  width: 100%;
  padding: 12px 14px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 16px;
  outline: none;
  transition: border 0.2s;
  box-sizing: border-box;
}

.login-box input:focus {
  border: 1px solid #409eff;
  box-shadow: 0 0 0 2px #eaf4ff;
}

.login-box input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.captcha-row {
  display: flex;
  gap: 10px;
  align-items: center;
  width: 100%;
  margin-bottom: 18px;
}

.captcha-row input {
  flex: 1;
  margin-bottom: 0;
}

.captcha-img {
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #e0e0e0;
}

.captcha-placeholder {
  height: 40px;
  width: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  color: #666;
}

.login-box button {
  width: 100%;
  padding: 12px;
  background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
  margin-bottom: 16px;
}

.login-box button:hover:not(:disabled) {
  background: linear-gradient(90deg, #3076c9 0%, #409eff 100%);
}

.login-box button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.error {
  color: #e74c3c;
  font-size: 14px;
  text-align: center;
  margin-bottom: 16px;
  background: #ffeaea;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #e74c3c;
  width: 100%;
  box-sizing: border-box;
}

.test-accounts {
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  width: 100%;
  box-sizing: border-box;
}

.test-accounts h4 {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 14px;
  text-align: center;
}

.account-item {
  margin-bottom: 6px;
  font-size: 12px;
  color: #888;
  text-align: center;
}

.account-item strong {
  color: #409eff;
}

@media (max-width: 480px) {
  .login-box {
    min-width: 320px;
    padding: 30px 20px;
  }
  
  .login-box h2 {
    font-size: 20px;
  }
}
</style>
